<?php

namespace App\Task;

use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\DataSpread;
use App\Model\DataUserClueToken;
use App\Model\DataUserJuliangTokenRel;
use App\Model\Payment;
use App\Model\Playlet;
use App\Model\PlayletEpisodes;
use GuzzleHttp\Client;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;

//#[Crontab(name: "wxUserRegister", rule: "*/10 * * * * *", callback: "execute", memo: "获取新注册的用户'")]
class WxUserRegisterTask
{
    protected LoggerInterface $logger;

    public static $token = '7FE11418980F94B82110648EC0DAFD2B';

    public static $reportUrl = "https://clue.oceanengine.com/outer/wechat/applet/token/1779984845733000";

    public static $startReportUrl = "https://ad.oceanengine.com/track/activate/";

    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'backhaulRegister');
    }

    public function execute()
    {
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------获取新注册的用户');
        //获取需要获取任务的视频
        $nowTime = date('Y-m-d H:i:s',time());
        $beforeTime = date('Y-m-d H:i:s',time()-(86400*2));
        $selectTime = date('Y-m-d H:i:s',time()-1800);
        try {

            $this->logger->info('获取所有拥有的微信的小程序');

            $appletData = Applet::query()->where(['type' => 1])->select(['id'])->get();
            if($appletData->isNotEmpty()){

                foreach ($appletData as $appletDatum) {

                    $applet_id = $appletDatum->id;
                    $this->logger->info('查询这个小程序的用户表',[$applet_id]);
                    $tokenData =Db::table('user_juliang_token_'.$applet_id)
                        ->select(['id','is_handle','xc_open_id','promotion_id','clue_token','aid','clickid','ut'])
                        ->where(['is_handle' => 'N'])
                        ->where('promotion_id','!=','0')
                        ->whereBetween('created_at',[$selectTime,$nowTime])->get();

                    if($tokenData->isNotEmpty()){
                        $this->logger->info('查询这个的用户表,用户数量为：',[$tokenData->count()]);
                        foreach ($tokenData as $tokenDatum){
                            //查询对应的user
                            $userInfo = Db::table('data_user_'.$applet_id)
                                ->where(['xc_open_id' => $tokenDatum->xc_open_id])
                                ->first();
                            $is_insert_association = false;
//                            var_dump($userInfo);
                            if(!empty($userInfo)){
                                //没有计划ID直接插入
                                if(empty($userInfo->ad_id)){
                                    Db::table('data_user_'.$applet_id)
                                        ->where(['id' => $userInfo->id])
                                        ->update(['ad_id' => $tokenDatum->promotion_id]);
                                    $is_insert_association = true;
                                    $this->logger->info('上报此用户的注册行为：',[$userInfo->id]);
                                    $this->uploadRegister($tokenDatum->clue_token,$userInfo->unionid,$userInfo->xc_open_id,$tokenDatum->clickid,$tokenDatum->ut);
                                }else{
                                    $this->logger->info('判断48小时之前是否有订单：',[$userInfo->id]);
                                    //判断48小时之前是否有订单
                                    $paymentInfo = Payment::query()->where(['applet_id' => $appletDatum->id,'user_id' => $userInfo->id])
                                        ->whereBetween('pay_time',[$beforeTime,$nowTime])
                                        ->exists();
                                    if(empty($paymentInfo)){
                                        $this->logger->info('更新订单ID：',[$userInfo->id]);
                                        Db::table('data_user_'.$applet_id)
                                            ->where(['id' => $userInfo->id])
                                            ->update(['ad_id' => $tokenDatum->promotion_id]);
                                        $is_insert_association = true;
                                    }
                                }
                                //插入用户和token关联表
                                if($is_insert_association){
                                    $this->logger->info('插入用户和token关联表');
                                    DataUserJuliangTokenRel::create([
                                        'applet_id' => $appletDatum->id,
                                        'user_id' => $userInfo->id,
                                        'user_juliang_token_id' => $tokenDatum->id,
                                        'aid' => $tokenDatum->aid
                                    ]);
                                }
                                $this->logger->info('更新token表已经处理此token');
                                Db::table('user_juliang_token_'.$applet_id)->where(['id' => $tokenDatum->id])->update(['is_handle' => 'Y']);
                            }else{
                                Db::table('user_juliang_token_'.$applet_id)->where(['id' => $tokenDatum->id])->update(['is_handle' => 'Y']);
                            }
                        }
                    }else{
                        $this->logger->error('没有用户需要上报');
                    }
                }
            }else{
                $this->logger->info('没有微信的小程序');
            }
        }catch (\Exception $e){
            $this->logger->error('请求上报出现问题|错误：' . $e->getLine() . '|' . $e->getMessage());
        }
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束获取新注册的用户');
    }
    public function getSign($nonce,$timestamp){
        $token = self::$token;
        $collect = [$token,$nonce,$timestamp];
        //获取token
        usort($collect,'strcmp');
        $signature = sha1(implode('',$collect));

        return $signature;
    }
    public function uploadRegister($clue_token,$union_id,$open_id,$clickid,$user_type){
        //普通用户
        if($user_type == 1){
            $params = [
                "clue_token" => $clue_token,
                "union_id"  => $union_id,
                "open_id"  => $open_id,
                "event_type"  => "0",
            ];
            $nonce = rand();
            $timestamp = time();
            $signature = $this->getSign($nonce,$timestamp);
            $linkUrl = self::$reportUrl.'?timestamp='.$timestamp.'&nonce='.$nonce.'&signature='.$signature;
            $this->logger->info('请求上报数据：'.PHP_EOL.var_export(['result' => $params], true));
            $this->logger->info('请求上报Url：'.$linkUrl);
            //开始上传
            $result  = $this->request($params, $linkUrl,'POST');
            if($result['status'] == 200 ){
                $this->logger->info('调用媒资接口成功 返回数据：'.PHP_EOL.var_export(['result' => $result], true));
            }else{
                $this->logger->error('调用媒资接口失败 返回数据：'.PHP_EOL.var_export(['result' => $result], true));
            }
        //星图
        }else{

            $params = [
                "callback" => $clickid,
                "event_type"  => "0",
            ];
            $linkUrl = self::$startReportUrl;
            $this->logger->info('请求星图上报数据：'.PHP_EOL.var_export(['result' => $params], true));
            $this->logger->info('请求星图上报Url：'.$linkUrl);
            //开始上传
            $result  = $this->request($params, $linkUrl,'POST');
            if($result['code'] == 0 ){
                $this->logger->info('调用星图接口成功 返回数据：'.PHP_EOL.var_export(['result' => $result], true));
            }else{
                $this->logger->error('调用星图接口失败 返回数据：'.PHP_EOL.var_export(['result' => $result], true));
            }

        }

        return false;
    }

    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       =['Content-Type' => 'application/json;charset=utf-8', 'Accept' => 'application/json','Accept-Charset' => 'utf-8'];
        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;
        }
//        var_dump($requestParams);
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}